unit uLocalRecorder;

interface

uses
  Windows, SysUtils, Classes, JvCreateProcess, uHHUtils;

const
  RECORD_RTMP_CMD = 'ffmpeg -copyinkf -loglevel quiet -i "%s live=1" -acodec copy -vcodec copy -f mp4 %s';

type
  TLocalRecorder = class
  private
    FRecording: Boolean;
    JvCreateProcess: TJvCreateProcess;
    procedure JvCreateProcessTerminate(Sender: TObject; ExitCode: Cardinal);
    procedure CreateJvProcess();
    procedure DestroyJvProcess();
  public
    constructor Create();
    destructor Destroy(); override;
    function StartRecord(AUrl: string; ASaveFileName: string): Boolean;
    procedure StopRecord();
  end;

implementation

{ TLocalRecorder }

constructor TLocalRecorder.Create;
begin
  CreateJvProcess();
  FRecording := False;
end;

procedure TLocalRecorder.CreateJvProcess;
begin
  JvCreateProcess := TJvCreateProcess.Create(nil);
  with JvCreateProcess do
  begin
    ConsoleOptions := [coRedirect, coSeparateError];
    CreationFlags := [cfNewConsole, cfUnicode];
    with StartupInfo do
    begin
      DefaultPosition := False;
      DefaultSize := False;
      DefaultWindowState := False;
      ShowWindow := swHide;
    end;
    WaitForTerminate := False;
  end;
  JvCreateProcess.OnTerminate := JvCreateProcessTerminate;
end;

destructor TLocalRecorder.Destroy;
begin
  DestroyJvProcess;
  inherited;
end;

procedure TLocalRecorder.DestroyJvProcess;
begin
  if Assigned(JvCreateProcess) then
  begin
    try
      JvCreateProcess.OnTerminate := nil;
      if JvCreateProcess.State <> psReady then
        JvCreateProcess.Terminate;
      JvCreateProcess.Free;
      JvCreateProcess := nil;
    except

    end;
  end;
end;

procedure TLocalRecorder.JvCreateProcessTerminate(Sender: TObject;
  ExitCode: Cardinal);
begin

end;

function TLocalRecorder.StartRecord(AUrl, ASaveFileName: string): Boolean;
var
  Param: string;
  Cmd: string;
begin
  if FRecording then
    StopRecord;
  Result := False;
  if Length(AUrl) <= 5 then
    Exit;

  if (JvCreateProcess.State <> psReady) then
  begin
    DestroyJvProcess;
    CreateJvProcess;
  end;

  Cmd := Format(AppPath + RECORD_RTMP_CMD,
    [AUrl, ASaveFileName]);

  JvCreateProcess.CommandLine := Cmd;
  JvCreateProcess.Run;
  Result := True;
  FRecording := True;
end;

procedure TLocalRecorder.StopRecord;
begin
  if FRecording then
  begin
    FRecording := False;
    JvCreateProcess.Write('q');
  end;
end;

end.
